package com.hwy.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * 下载工具类
 */
public class DownloadUtil {
    /**
     * 创建文件夹，如果存在就啥也不干
     *
     * @param path 文件夹所在地址
     */
    public static void createDir(String path) {
        Path dirPath = Paths.get(path);
        try {
            Files.createDirectories(dirPath);
            System.out.println("文件夹创建成功");
        } catch (IOException e) {
            System.out.println("文件夹创建失败");
            e.printStackTrace();
        }
    }

    /**
     * 将输入流中数据写入到文件中(图片)
     *
     * @param inputStream 输入流
     * @param outFilePath 输出文件地址
     */
    public static void createFileByInputStream(InputStream inputStream, String outFilePath) {
        // 输入流封装成缓冲流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 创建输出缓冲流
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outFilePath));
            byte[] bytes = new byte[2048];
            int flag;
            while ((flag = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, flag);
            }
            System.out.println("文件:" + outFilePath + "写入完成");
        } catch (IOException e) {
            System.out.println("创建输出流失败");
            e.printStackTrace();
        } finally {
            try {
                bufferedInputStream.close();
                if (Objects.nonNull(bufferedOutputStream)) {
                    bufferedOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
